const $config = require('../nuxt.config.js')
const $axios =require('../lib/axios'); 
const $redis = require("../lib/redis") // 你的redis配置文件路径
const timeago = require('../lib/timeago');

module.exports = function (Data) {
   
  Data.picture = function(picture){
    if(picture && picture.indexOf("http")!==0){
        picture = "https://img.snogogo.com/"+picture+"?imageView2/1/w/120/h/120";
    }
    return picture;
  }
  Data.getUserNameAndPictures= async function (p) {
      let args =[];
      if(p.length==0){
        return {};
      }
      let uids =[];
      
      for (const i in p) {
        if(args.indexOf("username_"+p[i])==-1){
          uids.push(p[i]);
          args.push("username_"+p[i]);
          args.push("picture_"+p[i]);
        }
      }
      let res =   await $redis.hmget("username_picture",args);
      ////console.log("uids:",uids,"res:",res);
      let users ={};
      let i =0;
      for ( i in uids) {
        let k  = Number(i)*2;
        let picture = Data.picture(res[k+1]);
        let user ={
           uid:uids[i],
           username:res[k],
           picture:picture,
        }
        // ////console.log("i:",i,k,"user:",user)
        if(user.username){
          users[uids[i]] = user;
        }
        
     }
      return users;
  }

    //  
    Data.getUser= async function (uid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer,
               withCredentials:false
             }
        }
        
        let res = await  $axios.get($config.axios.baseURL+"api/v3/users/"+uid+"?_uid="+$config.UID,headers);
        // let user = await $redis.hgetall("user:"+uid);
        // if(!user){
        //   return {
        //      code:1,
        //      msg:'User Not Found'
        //   }
        // }
        res.data.picture = Data.picture( res.data.picture);
         
        if(res.data.joindate){
          res.data.joindate= timeago( res.data.joindate );
        }
        res.data.phone = await $redis.get("uid:phone:"+uid);
        res.data.openid = await $redis.get("uid:openid:"+uid);
        // user['icon:text'] = user['username'].substr(0,1).toLocaleUpperCase()
        return res;
        
	};
    // 获取登录信息
    Data.sesData= async function (sid) {
       
        let sess = await $redis.get("ses"+sid);
      console.log("ses:",sess,"ses"+sid)
        if(sess){
          sess = JSON.parse(sess)
        } 
        let ses ={
          uid:0,
          uuid:0
        };
        if(sess && sess.passport && sess.passport.user){
          ses={
              uid: sess.passport.user,
              uuid:  sess.meta.uuid
          }
        }
        return ses;
    }

      // 获取登录信息
      Data.updateUser= async function (uid,row) {
        let i = await $redis.hmset("user:"+uid, row)
        return i;
      }
      
       // update a user accounthttps://community.nodebb.org/api/v3/users/{uid}
       Data.updateAccount= async function (uid,params={}) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer,
               withCredentials:false
             }
        }
        params._uid = $config.UID;
        let res = await  $axios.put($config.axios.baseURL+"api/v3/users/"+uid,params,headers);
        return res;
      }

      // 更新用户UserName
      Data.updateUserName= async function (uid,params={}) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer,
               withCredentials:false
             }
        }
        params._uid = $config.UID;
        let res = await  $axios.put($config.axios.baseURL+"api/v3/users/"+uid,params,headers);
        if(res.code==0){
           let set = {};
           set["username_"+uid] = params.username;
           let r = await $redis.hset("username_picture",set);
           ////console.log(r);
        }
        return res;
      }
      // https://community.nodebb.org/api/v3/users/{uid}/password
       // updatePassword
       Data.updatePassword= async function (uid,params={}) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer
             }
        }
        params._uid = $config.UID;
        let res = await  $axios.put($config.axios.baseURL+"api/v3/users/"+uid+"/password",params,headers);
        return res;
      }

      // Delete Account
      // https://community.nodebb.org/api/v3/users/{uid}/account
      Data.deleteAccount= async function (uid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer
             }
        }
        params._uid = $config.UID;
        let res = await  $axios.delete($config.axios.baseURL+"api/v3/users/"+uid+"/account",params,headers);
        return res;
      }
// generate a user token
      // https://community.nodebb.org/api/v3/users/{uid}/tokens
      Data.tokens= async function (uid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer
             }
        }
        // params._uid = sessionUid;
        let res = await  $axios.post($config.axios.baseURL+"api/v3/users/"+uid+"/tokens",{
          _uid:1
        },headers);
        return res;
      }
      //关注用户 
      Data.followUser= async function (uid,sessionUid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer
             }
        }
        // params._uid = sessionUid;
        let res = await  $axios.put($config.axios.baseURL+"api/v3/users/"+uid+"/follow",{
          _uid:sessionUid
        },headers);
        return res;
      }
       //un关注用户 
       Data.unFollowUser= async function (uid,sessionUid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer
             }
        }
        //  https://community.nodebb.org/api/v3/users/{uid}/follow
        let res = await  $axios.delete($config.axios.baseURL+"api/v3/users/"+uid+"/follow?_uid="+sessionUid,headers);
        return res;
      }
      // 判断是否关注
      Data.isFollowing=async function (uid,sessionUid) {
        let res = await $redis.zscore("following:"+sessionUid,uid);
        return res;
      }

      // notiCount
      Data.notiCount=async function (uid) {
        let count = await $redis.zcard("uid:"+uid+":notifications:unread")
        return count;
      }
      // https://community.nodebb.org/api/v3/users/
      //create a user 
      // {
// "username": "Dragon Fruit",
// "password": "s3cre7password",
// "email": "dragonfruit@example.org"
// }
      Data.createUser= async function (row) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer
             }
        }
        row._uid = $config.UID;
        let res = await  $axios.post($config.axios.baseURL+"api/v3/users",row,headers);
        return res;
      }
// https://community.nodebb.org/api/v3/users/{uid}/emails/{email}/confirm
      Data.validateEmail= async function (uid,email) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
               Authorization: bearer
             }
        }
       
        let post = {
          uid:uid,
          email:email,
          _uid:$config.UID
        }
        console.log("url",$config.axios.baseURL+"api/v3/users/"+uid+"/emails/"+email+"/confirm",post)
        let res = await  $axios.post($config.axios.baseURL+"api/v3/users/"+uid+"/emails/"+email+"/confirm",post,headers);
        return res;
      }
      // resetSend 发送重置密码邮件
      
      Data.resetSend= async function (p) {
        let params ={
            "resetSend":1,
            "birthday":"1989-10-01",
            "receive_email":p.email,
            "recaptcha_response":p.recaptcha_response,
            "recaptcha_type":p.recaptcha_type,
        }
        let res = await Data.updateAccount(1,params);
        return res;
      }

      // check reset code
      Data.checkResetCode= async function (code) {
        let p = await $redis.hget("reset:uid",code)
        return p;
      }



      // user category
      Data.createUserCategory= async function (uid=0,categoryName) {
        let args=["user:"+uid+":category"];
        let k =  new Date().getTime().toString().substr(-8);
        args.push( k+uid)
        args.push(categoryName)
        const foo = await $redis.zadd(...args)
        return foo;
    }
// 获取列表
    Data.getUserCategory= async function (uid=0,start=0,limit=10) {
      let list = await $redis.zrevrange("user:"+uid+":category",start, limit,"WITHSCORES");
      // console.log("list",list)
      return Data.zsetToObject( list);
    }

    Data.delUserCategory= async function (uid,name) {
      let score = await $redis.zscore("user:"+uid+":category",name)
      if(!score){
        return {
          code:1,
          msg:'not category'
        }
      }
      let list = await $redis.zrem("user:"+uid+":category",name );
      return  {
        code:0,
        msg:'suc',
        data:list
      };
    }

    Data.updateUserCategory= async function (uid,oldname,name) {
      let score = await $redis.zscore("user:"+uid+":category",oldname)
      if(!score){
        return {
          code:1,
          msg:'not category'
        }
      }
      let args=["user:"+uid+":category"];
  
      args.push( score)
      args.push(name)
      const foo = await $redis.zadd(...args)
      if(foo){
           await $redis.zrem("user:"+uid+":category",oldname );
      }
      return  {
        code:0,
        msg:'suc',
        data:foo
      };
    }


    Data.isAdministrators= async function (uid) {
      let userData = await Data.getUser(uid);
      console.log("userData:",userData)
      if(userData.data && userData.data.groupTitle && userData.data.groupTitle.indexOf("administrators")>-1){
        return true;
      }else{
        return false;
      }
    }
      
       
}